import axios from 'axios'
import { Message } from 'element-ui'
import {getToken, setToken} from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (getToken()){
      config.headers['Authorization'] = getToken()
    }
    return config
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.headers.authorization){
      setToken(response.headers.authorization)
    }
    return response.data;
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
